package vn.edu.saigontech.ncms.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;

@SuppressWarnings("unchecked")
public class ImportExport {

	public static void exportToPdfFile(String jasperFileName, Map params,
			Collection entries, String outputFileName) {
		try {
			JasperPrint jasperPrint = fillReport(jasperFileName, params,
					entries);
			JRPdfExporter pdfExporter = new JRPdfExporter();
			pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT,
					jasperPrint);
			pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
					outputFileName);
			pdfExporter.exportReport();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void exportToPdfStream(String jasperFileName, Map params,
			Collection entries, OutputStream output) {
		try {
			JasperRunManager.runReportToPdfStream(new FileInputStream(
					getReportLocation(jasperFileName)), output, params,
					new JRBeanCollectionDataSource(entries));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static JasperPrint fillReport(String jasperFileName, Map params,
			Collection entries) {
		try {
			return JasperFillManager.fillReport(
					getReportLocation(jasperFileName), params,
					new JRBeanCollectionDataSource(entries));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static String getReportLocation(String fileName) {
		return Global.INSTANCE.getParent().getParent() + File.separator
				+ "report" + File.separator + fileName;
	}
}